package com.ysy.filter;


import cn.dev33.satoken.filter.SaFilter;
import cn.dev33.satoken.stp.StpUtil;
import com.ysy.constant.RedisConstants;
import com.ysy.enums.ResponseCodeEnum;
import com.ysy.persimmons.common.constant.SecurityConstants;
import com.ysy.persimmons.common.exception.ServiceException;
import com.ysy.persimmons.common.util.StringUtils;
import io.jsonwebtoken.lang.Collections;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
public class HeaderFilter implements
GlobalFilter, Ordered
{

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * Header Token
     */
    private static final String TOKEN_HEADER_KEY = "Authorization";

    /**
     * Token前缀
     */
    private static final String TOKEN_HEADER_VALUE_PREFIX = "Bearer ";


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        List<String> headersList = request.getHeaders().get(TOKEN_HEADER_KEY);
        if (Collections.isEmpty(headersList)) {
            return chain.filter(exchange);
        }
        // 检验白名单

        String token = getToken(headersList.get(0));

        if (StringUtils.isBlank(token)){
            return chain.filter(exchange);
        }
        // 后续在研究StpUtil登录检查请求之前加入
       //  Object loginId = StpUtil.getLoginId();

        // 构建 Redis Key
        String tokenRedisKey = RedisConstants.SA_TOKEN_TOKEN_KEY_PREFIX + token;
        // 查询 Redis, 获取用户loginId
        Integer loginId = (Integer) redisTemplate.opsForValue().get(tokenRedisKey);
        log.info("当前请求的用户id={}", loginId);
        if (loginId == null){
            return chain.filter(exchange);
        }
        mutate.header(SecurityConstants.DETAILS_USER_ID, String.valueOf(loginId));

        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    public String getToken(String token) {
        if (StringUtils.isBlank(token) || !token.contains(TOKEN_HEADER_VALUE_PREFIX)) {
            return null;
          //  throw new ServiceException(ResponseCodeEnum.NO_LOGIN_CHECK);
        }
        return token.replace(TOKEN_HEADER_VALUE_PREFIX, "");
    }

    @Override
    public int getOrder() {
        return 10;
    }
}
